package com.wswy.wyjk.ui.login;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.geetest.sdk.GT3ConfigBean;
import com.geetest.sdk.GT3ErrorBean;
import com.geetest.sdk.GT3GeetestUtils;
import com.geetest.sdk.GT3Listener;
import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseUtils.Toast;
import com.my.httpapi.api.baseView.BaseMVPActivity;
import com.tencent.mmkv.MMKV;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Api;
import com.wswy.wyjk.api.Constant;
import com.wswy.wyjk.api.MMKVConstant;
import com.wswy.wyjk.api.OldApi;
import com.wswy.wyjk.api.entity.AdverConfigEntity;
import com.wswy.wyjk.api.entity.DeviceMod;
import com.wswy.wyjk.api.entity.RequestParameter;
import com.wswy.wyjk.ui.login.Dialog.PicVerificationDialog;
import com.wswy.wyjk.ui.login.Interface.ILogin;
import com.wswy.wyjk.ui.login.Presenter.LoginPresenter;
import com.wswy.wyjk.ui.login.model.CaptchaData;
import com.wswy.wyjk.ui.login.model.CaptchaValidData;
import com.wswy.wyjk.ui.login.model.LoginResponse;
import com.wswy.wyjk.ui.login.model.SendPicResponse;
import com.wswy.wyjk.ui.login.model.VerificationPicResponse;
import com.wswy.wyjk.ui.main.WebViewActivity;
import com.wswy.wyjk.ui.main.event.InfoEvent;
import com.wswy.wyjk.ui.main.event.RankEvent;
import com.wswy.wyjk.ui.main.event.RankFinishEvent;
import com.wswy.wyjk.ui.practiceNew.Dialog.CustomDialog;
import com.wswy.wyjk.ui.practiceNew.PracticeNewActivity;
import com.wswy.wyjk.ui.splash.SplashController;
import com.wswy.wyjk.utils.GeetestUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ViewL(R.layout.layout_login)
public class LoginActivity extends BaseMVPActivity<LoginPresenter, BaseMVPActivity> implements ILogin.IView {

    private TextView tvLogin, tvCode, tvClosed, tvXieyi, tvYinsi;
    private ImageView ivCheck;
    private EditText etPhone, etCode;
    private boolean isCheck = false;
    private boolean isGee = false;
    private SplashController splashController;

    @Override
    protected void initData(Bundle savedInstanceState) {
        initView();
        initData();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return true;
    }

    @Override
    public void onBackPressed() {
        close();
    }

    @Override
    protected void destroy() {
        presenter.timeEnd();
        if (isGee) {
            GeetestUtils.onDestroy();
        }
    }

    private void initView() {
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        tvClosed = findViewById(R.id.tv_closed);
        tvLogin = findViewById(R.id.tv_login);
        ivCheck = findViewById(R.id.iv_check);
        tvCode = findViewById(R.id.tv_code);
        tvXieyi = findViewById(R.id.tv_xieyi);
        tvYinsi = findViewById(R.id.tv_yinsi);
    }

    private void initData() {
        splashController = new SplashController(getApplicationContext(), null);
        //清空token
        MMKV.defaultMMKV().encode(MMKVConstant.TOKEN, "");
        String savePhone = MMKV.defaultMMKV().decodeString(MMKVConstant.PHONE);
        if (!TextUtils.isEmpty(savePhone)) {
            etPhone.setText(savePhone);
            etPhone.setSelection(savePhone.length());
        }
        tvClosed.setOnClickListener(view -> close());
        tvXieyi.setOnClickListener(view -> gotoWebView("用户协议"));
        tvYinsi.setOnClickListener(view -> gotoWebView("隐私政策"));

        tvLogin.setOnClickListener(view -> {
            String phone = etPhone.getText().toString();
            String code = etCode.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                Toast.show("请输入手机号码");
                return;
            }

            if (TextUtils.isEmpty(code)) {
                Toast.show("请输入验证码");
                return;
            }
            if (!isCheck) {
                Toast.show("请勾选用户协议和隐私政策");
                return;
            }
            requestLogin(phone, code);
        });

        tvCode.setOnClickListener(view -> {
            String phone = etPhone.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                Toast.show("请输入手机号码");
                return;
            }
            //判断是否存在uuid
            if(TextUtils.isEmpty(SPUtils.getInstance().getString(Constant.SP_UUID_KEY))){
                presenter.requestDevice(RequestParameter.generate().addAll(splashController.getDeviceInfoMap()).getUUIDParams());
            }else{
                presenter.getCaptcha();
            }
        });

        ivCheck.setOnClickListener(view -> {
            if (isCheck) {
                isCheck = false;
                ivCheck.setBackgroundResource(R.drawable.login_single_nor);
            } else {
                isCheck = true;
                ivCheck.setBackgroundResource(R.drawable.login_single);
            }
        });
    }


    private void close() {
        EventBus.getDefault().post(new RankFinishEvent());
        finish();
    }

    private void gotoWebView(String type) {
        Map map = new HashMap();
        map.put("type", type);
        intent(WebViewActivity.class, map);
    }

    private void requestLogin(String phone, String code) {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("code", code);
        presenter.login(map);
    }

    @Override
    public void timeOnTick(long millisUntilFinished) {
        tvCode.setText(millisUntilFinished / 1000 + "秒");
        tvCode.setClickable(false);
        tvCode.setTextColor(getResources().getColor(R.color.color_808080));
    }

    @Override
    public void timeFinish() {
        tvCode.setText("重新获取验证码");
        tvCode.setClickable(true);
        tvCode.setTextColor(getResources().getColor(R.color.blue));
    }

    @Override
    public void getCaptcha(CaptchaData captchaData) {
        presenter.showTCDialog(captchaData, etPhone.getText().toString());
    }

    @Override
    public void validCaptchaTc(CaptchaValidData captchaValidData) {
        presenter.requestCode(etPhone.getText().toString(), captchaValidData.getTicket());
    }

    @Override
    public void login(LoginResponse loginResponse) {
        //保存信息
        MMKV.defaultMMKV().encode(MMKVConstant.TOKEN, loginResponse.token);
        MMKV.defaultMMKV().encode(MMKVConstant.NAME, loginResponse.userName);
        MMKV.defaultMMKV().encode(MMKVConstant.NICKNAME, loginResponse.nickName);
        MMKV.defaultMMKV().encode(MMKVConstant.HeadImg, loginResponse.headImg);
        MMKV.defaultMMKV().encode(MMKVConstant.PHONE, etPhone.getText().toString());
        //通知页面
        EventBus.getDefault().post(new InfoEvent());
        EventBus.getDefault().post(new RankEvent());
        finish();
    }

    @Override
    public void isGee(Boolean b) {
        isGee = b;
    }

    @Override
    public void geeData(String str) {
        presenter.requestCode(etPhone.getText().toString(), str);
    }

    @Override
    public void geePic(SendPicResponse sendPicResponse) {
        new PicVerificationDialog.Builder(LoginActivity.this).setPicStr(sendPicResponse.getImage())
                .setPositiveButton(content -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("tag", sendPicResponse.getTag());
                    map.put("code", content);
                    presenter.verSend(map);
                }).create().show();
    }

    @Override
    public void verPic(VerificationPicResponse verificationPicResponse) {
        presenter.requestCode(etPhone.getText().toString(), verificationPicResponse.getTicket());
    }

    @Override
    public void getUUID(DeviceMod deviceMod){
        if (deviceMod != null && !TextUtils.isEmpty(deviceMod.uuid)) {
            SPUtils.getInstance().put(Constant.SP_UUID_KEY, deviceMod.uuid);
            presenter.getCaptcha();
        }
    }
}
